package org.jeecg.modules.gzgl.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.zhaodui.fxy.*;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.gzgl.entity.*;
import org.jeecg.modules.gzgl.service.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.gzgl.vo.FxjGzgl01PageBatch;
import org.jeecg.modules.gzgl.vo.FxyGzgl04Page;
import org.jeecg.modules.system.service.impl.SysDataLogServiceImpl;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;

 /**
 * @Description: 公证订单主表
 * @Author: zhaodui
 * @Date:   2020-02-06
 * @Version: V1.0
 */
@RestController
@RequestMapping("/gzgl/fxyGzgl01")
@Slf4j
public class FxyGzgl01Controller extends JeecgController<FxyGzgl01, IFxyGzgl01Service> {
	@Autowired
	private IFxyGzgl01Service fxyGzgl01Service;
	 @Autowired
	 private SysDataLogServiceImpl sysDataLogService;
	 @Autowired
	 private FxyGzgl04Controller fxyGzgl04Controller;
	 @Autowired
	 private IFxyGzgl04Service fxyGzgl04Service;
	 @Autowired
	 private RedisUtil redisUtil;
	/**
	 * 分页列表查询
	 *
	 * @param fxyGzgl01
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	public Result<?> queryPageList(FxyGzgl01 fxyGzgl01,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<FxyGzgl01> queryWrapper = QueryGenerator.initQueryWrapper(fxyGzgl01, req.getParameterMap());
		Page<FxyGzgl01> page = new Page<FxyGzgl01>(pageNo, pageSize);
		IPage<FxyGzgl01> pageList = fxyGzgl01Service.page(page, queryWrapper);
		return Result.ok(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param fxyGzgl01
	 * @return
	 */
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody FxyGzgl01 fxyGzgl01) {

		fxyGzgl01Service.save(fxyGzgl01);
		Gson gs = new GsonBuilder().serializeNulls().create();
		String datacont = gs.toJson(fxyGzgl01);
		String id = fxyGzgl01.getId();
		sysDataLogService.addDataLog("fxy_gzgl_01",id,  datacont);
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param fxyGzgl01
	 * @return
	 */
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody FxyGzgl01 fxyGzgl01) {

		if (StringUtil.isEmpty(fxyGzgl01.getQuery39())||fxjConstant.iscommitfxy.equals(fxyGzgl01.getQuery39())) {//不提交法信
			fxyGzgl01Service.updateById(fxyGzgl01);
			return Result.ok("编辑成功！");
		}

		commitbatch(fxyGzgl01.getId());//批量提交合同到公证

		fxyGzgl01Service.updateById(fxyGzgl01);
		Gson gs = new GsonBuilder().serializeNulls().create();
		String datacont = gs.toJson(fxyGzgl01);
		String id = fxyGzgl01.getId();
		sysDataLogService.addDataLog("fxy_gzgl_01",id,  datacont);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		fxyGzgl01Service.removeById(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.fxyGzgl01Service.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		FxyGzgl01 fxyGzgl01 = fxyGzgl01Service.getById(id);
		if(fxyGzgl01==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(fxyGzgl01);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param fxyGzgl01
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, FxyGzgl01 fxyGzgl01) {
        return super.exportXls(request, fxyGzgl01, FxyGzgl01.class, "公证订单主表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, FxyGzgl01.class);
    }

	 public void commitbatch(String id){
		 FxyGzgl01 fxyGzgl01 = fxyGzgl01Service.getById(id);
		 List<FxyGzgl04> list04 = fxyGzgl04Controller.get04by07(fxyGzgl01.getQuery07());
		 FxyGzgl04 fxyGzgl04 = list04.get(0);
			try {
				String appCode = fxyGzgl01.getQuery01();
				fxyUser fxyUser = new fxyUser();

				fxyUser.setCaseNumber(fxyGzgl04.getQuery16());
				fxyUser.setUserId(fxyGzgl04.getQuery14());
				fxyUser.setOrgId(fxyGzgl04.getQuery20());
				fxyUser.setBusinessType(fxyGzgl04.getQuery21());
				fxyUser.setProcessNumber(fxyGzgl04.getQuery15());
				fxyUser.setSendAgreement(fxyGzgl04.getQuery19());
				List<fxyUser> fxyUserList = new ArrayList<>();
 				for (FxyGzgl04 tp : list04) {
					fxyUser fxy = new fxyUser();
					fxy.setAgreementCode(tp.getQuery22());
					fxy.setTemplateCode(tp.getQuery23());
					fxy.setAgreementName(tp.getQuery24());
					List<FxyGzgl05> fxyGzgl05List =  new ArrayList<>();
					List<FxyGzgl02> fxyGzgl02List =  new ArrayList<>();
					List<FxyGzgl03> fxyGzgl03List =  new ArrayList<>();
					//如果数据为空则从系统获取
					//如果数据为空则从系统获取
					if(fxyGzgl02List!=null&&fxyGzgl02List.size()==0){
						fxyGzgl02List = fxyGzgl04Controller.get02by0708(tp.getQuery07(),tp.getQuery08());
					}
					if(fxyGzgl03List!=null&&fxyGzgl03List.size()==0){
						fxyGzgl03List = fxyGzgl04Controller.get03by0708(tp.getQuery07(),tp.getQuery08());
					}
					if(fxyGzgl05List!=null&&fxyGzgl05List.size()==0){
						fxyGzgl05List = fxyGzgl04Controller.get05by0708(tp.getQuery07(),tp.getQuery08());
					}
					List<conmap> conmapList = new ArrayList<conmap>();
					for (FxyGzgl05 t : fxyGzgl05List) {
						conmap con = new conmap();
						con.setConKey(t.getQuery15());
						con.setConValue(t.getQuery17());
						conmapList.add(con);
					}
					fxyUser.setConmapList(conmapList);
					String userids = "";
					String signs = "";
					for (FxyGzgl02 t2 : fxyGzgl02List) {
						userids = userids + t2.getQuery20() + ",";
						signs = signs + t2.getQuery13() + ",";
					}
					for (FxyGzgl03 t3 : fxyGzgl03List) {
						userids = userids + t3.getQuery24() + ",";
						signs = signs + t3.getQuery12() + ",";
					}
					fxy.setUserIds(userids);
					fxy.setSignatorys(signs);
					fxyUserList.add(fxy);
				}

				agreementres res = fxyUtil.addAgreementByProcessNumberreturnobjectbatch(appCode, redisUtil, fxyUser, fxyUserList);
				if (!StringUtil.isEmpty(res.getResultCode())) {
					fxyGzgl04.setQuery16(res.getResultData().getCaseNumber());//案件编号
					fxyGzgl04.setQuery17(res.getResultData().getWritInfos().get(0).getWritNumber());//批次编号
					fxyGzgl04.setQuery18(res.getResultData().getWritInfos().get(0).getAgreementInfos().get(0).getStorageNo());//存证编号
					List<agreementres.ResultDataBean.WritInfosBean> writInfos = res.getResultData().getWritInfos();
					for (FxyGzgl04 tpsave : list04) {
						FxyGzgl04 fxyGzgl04save = new FxyGzgl04();
						BeanUtils.copyProperties(tpsave, fxyGzgl04save);
						fxyGzgl04save.setQuery16(fxyGzgl04.getQuery16());//案件编号
						fxyGzgl04save.setQuery17(writInfos.get(0).getWritNumber());//案件编号
						String wsbh = fxyGzgl04save.getQuery22();//文书编号
						List<agreementres.ResultDataBean.WritInfosBean.AgreementInfosBean> agreementInfos = writInfos.get(0).getAgreementInfos();
						for (agreementres.ResultDataBean.WritInfosBean.AgreementInfosBean ta : agreementInfos) {
							if (ta.getAgreementCode().equals(wsbh)) {
								fxyGzgl04save.setQuery18(ta.getStorageNo());//存证编号
							}
						}
						fxyGzgl04Service.updateById(fxyGzgl04save);
					}
				}
			} catch (BaseBusinessException e) {

			}
	}

}
